package com.taoyibao.hongcanting.receiver;

import android.app.DownloadManager;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.support.v4.content.FileProvider;
import android.text.TextUtils;

import com.taoyibao.hongcanting.cache.SpUtils;
import com.taoyibao.hongcanting.constant.CodeConstant;
import com.taoyibao.hongcanting.event.EventInstallApk;
import com.taoyibao.hongcanting.utils.LogUtils;

import org.greenrobot.eventbus.EventBus;

import java.io.File;

import static android.content.Context.DOWNLOAD_SERVICE;

/**
 * @author TangAnna
 * @description: 下载完成的广播
 * @date :${DATA} 10:14
 */
public class DownApkReceiver extends BroadcastReceiver {
    private static final String TAG = "DownApkReceiver";
    private DownloadManager mManager;
    private Context mContext;

    @Override
    public void onReceive(Context context, Intent intent) {
        mContext = context;
        if (intent.getAction().equals(DownloadManager.ACTION_DOWNLOAD_COMPLETE)) {
            long downloadApkId = intent.getLongExtra(DownloadManager.EXTRA_DOWNLOAD_ID, -1L);
            long saveApkId = SpUtils.getDownloadId();
            if (downloadApkId == saveApkId) {
                checkDownloadStatus(context, downloadApkId);
            }
        }
    }

    private void checkDownloadStatus(Context context, long downloadId) {
        mManager = (DownloadManager) context.getSystemService(DOWNLOAD_SERVICE);
        DownloadManager.Query query = new DownloadManager.Query();
        query.setFilterById(downloadId);
        Cursor cursor = mManager.query(query);
        if (cursor.moveToFirst()) {
            int status = cursor.getInt(cursor.getColumnIndex(DownloadManager.COLUMN_STATUS));
            switch (status) {
                case DownloadManager.STATUS_SUCCESSFUL:
                    EventInstallApk eventInstallApk = new EventInstallApk();
                    eventInstallApk.isSucess = true;
                    EventBus.getDefault().post(eventInstallApk);
                    break;
                case DownloadManager.STATUS_FAILED:
                    LogUtils.dNormal(TAG, "下载失败.....");
                    break;
                case DownloadManager.STATUS_RUNNING:
                    LogUtils.dNormal(TAG, "正在下载.....");
                    break;
                default:
                    break;
            }
        }
    }

    private void installApk(Context context) {
        String apkName = SpUtils.getApkName();
        if (!TextUtils.isEmpty(apkName)) {
            LogUtils.dNormal(TAG, "apkName 为" + apkName);
            File file = context.getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS + "/" + apkName);
            if (file != null) {
                Uri uri;
                Intent install = new Intent("android.intent.action.VIEW");
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) { //如果是7.0以上的系统，要使用FileProvider的方式构建
                    uri = FileProvider.getUriForFile(mContext, CodeConstant.PROVIDER_STR, file);
                } else {
                    uri = Uri.fromFile(file);
                }
                install.setDataAndType(uri, "application/vnd.android.package-archive");
                install.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                install.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
                context.startActivity(install);
            } else {
                LogUtils.dNormal(TAG, "下载失败");
            }
        } else {
            LogUtils.dNormal(TAG, "apkName 为 null");
        }
    }
}
